package com.game.common.utils.code;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.Random;

@Slf4j
public class CodeUtil {
    public static String enCode(String password, String key, byte[] salt) {
        if (password == null || password.isEmpty()) {
            return "";
        } else {
            byte[] input = password.getBytes();
            try {
                byte[] data = PBECoder.encrypt(input, key, salt);
                return PBECoder.encryptBASE64(data);
            } catch (Exception e) {
                log.error("加密失败:" + e.getMessage());
            }
        }
        return "";

    }

    public static String enCodeWithBCrypt(String inputString) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String hashedPassword = passwordEncoder.encode(inputString);
        return hashedPassword;
    }

    //第一个参数传加密之前的，第二个传重新加密的
    public static boolean matchesWithBCrypt(String inputString1, String inputString2) {

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(inputString1, inputString2);
    }

    /**
     * 生成n位数密码
     *
     * @return
     */
    public static String createCode(int length) {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < length; i++) {
            Random random = new Random();
            str.append(random.nextInt(9));
        }
        return str.toString();
    }


}
